﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using IDotNet;
using LZL.IISManage;
using LZL.IISWeb.Model;

namespace LZL.IISWeb.Core
{
    public class IISWebConfig
    {
        public static Dictionary<string, List<string>> GetSites()
        {
            var dict = new Dictionary<string, List<string>>();
            var iis = WebConfigurationManager.GetSection("iisWebConfig") as IISWebsSection;
            if (iis == null)
            {
                return dict;
            }
            foreach (IISWebElement iisWeb in iis.IISWebs)
            {
                if (iisWeb.ID > 0)
                {
                    dict.Add(iisWeb.ID.ToString(), iisWeb.WebSeconds.Cast<IISWebSecondElement>().Select(p => p.Path).ToList());
                }
            }
            return dict;
        }

        public static bool HasWebPerm(Dictionary<string, List<string>> config, long webId, string path = null)
        {
            if (config.Count == 0)
            {
                return true;
            }
            if (!config.ContainsKey(webId.ToString()))
            {
                return false;
            }
            if (path == null)
            {
                return true;
            }
            var p = config[webId.ToString()];
            if (p.IsNullOrEmpty())
            {
                return true;
            }
            return p.Contains(path, StringComparer.OrdinalIgnoreCase);
        }

        public static bool HasAppPoolConfigPerm(List<IISSiteInfo> list, string appPoolName)
        {
            if (list.IsNullOrEmpty() || appPoolName.IsNullOrWhiteSpace())
            {
                return false;
            }
            var sites = GetSites();
            foreach (var item in list)
            {
                if (!IISWebConfig.HasWebPerm(sites, item.Index)) continue;
                foreach (var info in item.Applications)
                {
                    if (!IISWebConfig.HasWebPerm(sites, item.Index, info.Path)) continue;
                    if (info.PoolName.Equals(appPoolName))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

    }
}